#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
import sys
import time
import re
from flask import Flask
from flask import render_template
from flask import request


app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    learn_date = request.args.get("learn_date")
    if not learn_date:
        learn_date = time.strftime("%Y%m%d")
    output_str = learn_date
    wordsTest = WordsTest()
    result = wordsTest.get_words(learn_date)
    wordsTest.end()
    i = 1
    for item in result:
        output_str = output_str+"<br>"+str(i)+". "+item
        i = i+1
    return output_str

@app.route('/check', methods=['GET'])
def check():
    learn_date = request.args.get("learn_date")
    if not learn_date:
        learn_date = time.strftime("%Y%m%d")
    output_str = learn_date + '<pre>'
    wordsTest = WordsTest()
    result = wordsTest.get_words_explains(learn_date)
    wordsTest.end()
    if not result:
        output_str = output_str+' None'
    else:
        i = 1
        for item in result:
            output_str = output_str+"<br><strong>"+str(i)+"</strong>. "+item
            i = i+1
    return output_str+'</pre>'

class WordsTest:
    def __init__(self):
        self.conn = sqlite3.connect('data.db')
        self.cursor = self.conn.cursor()
        self.result_words = []
        self.result_words_explains = []
    def get_words(self, learn_date):
        self.cursor.execute('select * from words where learn_date = \''+learn_date+'\'')
        result = self.cursor.fetchall()
        if not result:
            self.cursor.execute('select * from words where learn_date is NULL order by id asc limit 50')
            result = self.cursor.fetchall()
            if not result or len(result) < 10:
                result = [[0,'words not enough!']]
            else:
                for item in result:
                    self.cursor.execute('update words set  learn_date = \''+learn_date+'\' where word = \''+item[1]+'\'')
        return self.set_words(result)
    def set_words(self, result):
        for item in result:
            self.result_words.append(item[1])
        return self.result_words
    def get_words_explains(self, learn_date):
        self.cursor.execute('select * from words where learn_date = \''+learn_date+'\'')
        result = self.cursor.fetchall()
        if result:
            for item in result:
                fileter_text = re.sub('\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]', '', item[3])
                self.result_words_explains.append(fileter_text)
        return self.result_words_explains
    def end(self):
        self.cursor.close()
        self.conn.commit()
        self.conn.close()


if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf8')
    app.debug = True
    app.port = 5001
    app.run()

